//index.js
//获取应用实例
const app = getApp()
var arr = []
var saveObj={}
Page({
  data: {
    viewList: 0,
    loading: false,
    catid:0,
    viewArr: [],
    itemTitle: '',
    username: '',
    readeNum: '',
    contentViewOneImgTitle: '',
    types: 2,
    newsList:[],
    domeList: [],
    noContent:false,
    height:"",
    layer:false,
    hotOne:false,
    hotThree: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    loginSign:{},
    hotAnt:false,
    usericon:'',
    redmoney:'',
    myUid:"",
  },
  onLoad: function(e) {
    let that =this
    var userInfo = wx.getStorageSync("userData")
    wx.showLoading({
      title:"正在加载"
    })
    if (userInfo){ // 存在本地缓存
    console.log("有缓存")
      this.resizeData(userInfo)
    }else{ // 不存在本地缓存
      console.log("没有缓存")
      this.checkUserInfo()
    }
    if (e.uid){
      this.setData({
        myUid: e.uid
      }, function () {
        that.callBackFn()
      })
    }else{
      that.callBackFn()
    }
    if(wx.getStorageSync("err")){
      this.setData({
        hotOne:true,
      })
    }
  },
  callBackFn:function(res){  // 获取 app.js 的内容的回调函数
    this.requestId()
    this.requestList()
    this.startlogin()
  },
  requestId:function(){ // 请求列表tabItem
    var that = this
    var tabItemUrl = 'https://kandian.youth.cn:8181/WechatApp/Article/category.json?' + app.makeUrl(app.globalData.allInfo)
    var addObj = { id: "0", name: "推荐" }
    console.log(tabItemUrl)
    wx.request({
      url: tabItemUrl,
      data:{
        sign: app.makeSign(app.globalData.allInfo)
      },
      success: function (res) {
        console.log("请求列表")
        console.log(res)
        var newArr = res.data.items.unshift(addObj)
        that.setData({
          viewArr: res.data.items 
        })
      }
    })
  },
  requestList:function(){ // 请求列表数据
    arr=[]
    var that = this;
    var nowTime = new Date().getTime()
    app.globalData.allInfo.catid = that.data.catid;
    app.globalData.allInfo.nowTime = nowTime;
    app.globalData.allInfo.op = "1";
    var requestList = 'https://kandian.youth.cn:8181/WechatApp/Article/Lists.json?' + app.makeUrl(app.globalData.allInfo)
    var requestListSign = app.makeSign(app.globalData.allInfo)
    wx.request({
      url: requestList,
      data:{
        sign: requestListSign
      },
      success(res){
        console.log("请求列表")
        console.log(res)
        
        wx.hideLoading()
        if (res.data.items&&res.data.items.length>0){
          that.timerData(res.data.items,true)
          //储存数据 
          that.saveDataList(that.data.catid, res.data.items)
        }
      }
    })
  },
  itemClick: function(e) { // 切换栏目
    let that = this;
    wx.showLoading({
      title: "正在加载"
    })
    this.setData({
      viewList: e.target.dataset.index,
      catid: e.target.dataset.id
    })
    if (that.saveDataList(that.data.catid)){ // 切换是检查本地数据，防止每次切换都请求新数据
        this.setData({
          newsList: saveObj[that.data.catid]
        })
        wx.hideLoading()
    }else{
      this.requestList()
    }
  },
  goDetails: function(e) { // 进入详情页
  console.log(e)
    wx.navigateTo({
      url: '../newDetails/newDetails?pageId='+e.currentTarget.dataset.pageid
    })
  },
  onPullDownRefresh(){ //下拉刷新  
    var that = this;
    var nowTime = new Date().getTime()
    app.globalData.allInfo.catid = that.data.catid;
    app.globalData.allInfo.nowTime = nowTime;
    app.globalData.allInfo.op="0";
    var requestNewList = 'https://kandian.youth.cn:8181/WechatApp/Article/Lists.json?' + app.makeUrl(app.globalData.allInfo)
    var requestListNewSign = app.makeSign(app.globalData.allInfo)
    wx.request({
      url: requestNewList,
      data: {
        sign: requestListNewSign,
      },
      success(res) {
        console.log("下拉刷新")
        console.log(res)
        wx.stopPullDownRefresh()
        if (res.data.items && res.data.items.length > 0) {
          that.timerData(res.data.items, true)
          console.log(that.data.catid)
          console.log(saveObj)
          saveObj[that.data.catid] = that.data.newsList
        }
      }
    })
  },

  onReachBottom(){
    var that = this;
    that.setData({
      loading: true
    })
    var nowTime = new Date().getTime()
    app.globalData.allInfo.catid = that.data.catid;
    app.globalData.allInfo.nowTime = nowTime;
    app.globalData.allInfo.op="1"
    var requestNewList = 'https://kandian.youth.cn:8181/WechatApp/Article/Lists.json?' + app.makeUrl(app.globalData.allInfo)
    var requestListNewSign = app.makeSign(app.globalData.allInfo)
    wx.request({
      url: requestNewList,
      data: {
        sign: requestListNewSign,
      },
      success(res) {
        if (res.data.items && res.data.items.length > 0) {
            that.timerData(res.data.items)
        }else{ //没数据重新请求
          that.onReachBottom()
        }
      }
    })
  },
  onShareAppMessage(){// 分享
    return {
      title: '中青看点新闻',
      path: 'pages/news/news'
    }
  },
 timerData:function(data,type){ // 处理数据
   var nowTimer = new Date().getTime()
   var that = this;
   var html = "";
   data.map(function (item, index){
     var day = parseInt((nowTimer - item.behot_time) / 1000 / 60 / 60 / 24)
     var hours = parseInt((nowTimer - item.behot_time) / 1000 / 60 / 60 % 24)
     var minutes = Math.ceil((nowTimer - item.behot_time) / 1000 / 60 % 60)
     var time = parseInt((nowTimer - item.behot_time) / 1000 % 60)
     var html = `${minutes} 分钟前`
     item.downTime = html
     type?arr.unshift(item):arr.push(item)
   })
   arr.map((item,index)=>{
     item.downTime = `${Math.ceil((nowTimer - item.behot_time) / 1000 / 60 % 60)} 分钟前`
   })
   that.setData({
     newsList: arr,
     loading: false
   })
 },
  saveDataList:function(id,obj){// 缓存数据
    if (saveObj[id]){ //存在缓存数据
      return true 
      }else{
      obj ? saveObj[id] = obj :""
       return false
      }
  },
 //  op   catid   // uid  sign  device_type behot_time   手机品牌    手机型号 微信版本号 操作系统版本 客户端平台 fontSizeSetting


  bindGetUserInfo: function (e) { //获取用户信息
    console.log(e)
    let that = this;
    wx.login({
      success:data=>{
        wx.showLoading({
          title: '登录中'
        })
        setTimeout(function () {
          wx.hideLoading()
        }, 500)
        that.setData({
          layer: true,
          hotOne: false,
          hotThree: true,
        })
        that.login(e.detail,data.code)
      }
    })
 
  },
  closeLayer:function(){
    this.setData({
      layer:false,
      hotThree:false,
    })
  },
  startlogin:function(){
    delete app.globalData.systemInfo.code
    delete app.globalData.systemInfo.encryptedData
    delete app.globalData.systemInfo.iv
    delete app.globalData.systemInfo.sign
    var startObj = app.globalData.systemInfo;
    console.log('公共参数',startObj)
    console.log('uid', this.data.myUid)
    
    startObj.uid = app.globalData.userInfo.uid
    startObj.channel = "6666";
    startObj.invite_id = this.data.myUid;
    var signurl = 'https://kandian.youth.cn:8181/WechatApp/Wechat/start.json?' + app.makeUrl(startObj)
    wx: wx.request({
      url: signurl, 
      data: {
        sign: app.makeSign(startObj)
      },
      success: function (res) {
        console.log('0.000000', res.data)
      },
    })
  },
  checkUserInfo:function(){ // 检查是否授权
    let that = this;
    // 查看是否授权
    wx.login({
      success:data=>{
        wx.getSetting({
          success: function (res) {
            if (res.authSetting['scope.userInfo']) {// 授权
              console.log("授权")
              that.setData({
                layer: false,
                hotOne: false,
              })
              wx.getUserInfo({
                success: function (res) {
                  console.log(res)
                  that.login(res,data.code)
                }
              })
            } else { // 未授权
              console.log("未授权")
              that.setData({
                layer: true,
                hotOne: true,
              })
            }
          }
        })
      }
    })
  },
  login: function (e,code) { // 登录换取个人信息
    var that = this
    var obj = {}
    var urlData={} 
    var allPrams = app.globalData.systemInfo
    that.setData({
      loginSign:e
    })
        if (code) {
          that.data.loginSign.code = code
          urlData =  allPrams
          urlData.code = code
          urlData.encryptedData = that.data.loginSign.encryptedData
          urlData.iv = that.data.loginSign.iv
          urlData.signature = that.data.loginSign.signature
          delete urlData.errMsg 
          urlData.sign = app.makeSign(urlData)
          var loginUrl = "https://kandian.youth.cn:8181/WechatApp/Wechat/login.json";
          wx.request({
            url: loginUrl,
            data: urlData,
            method: 'POST',
            header: {
              "Content-Type": "application/x-www-form-urlencoded"
            },
            success: function (res) {// 拿到用户信息，进行储存
              if (!res.data.items){
                console.log("解密失败")
                that.setData({
                  hotOne:true,
                  hotThree:false,
                })
                wx.showToast({
                  title: '登录失败',
                  duration:1000,
                })
                wx.setStorageSync("err", true)
                return false
              }
              wx.clearStorageSync("err")
              // 本地储存数据
              wx.setStorageSync("userData",res.data.items)
              // 处理数据
              that.resizeData(res.data.items)
              console.log(res.data.items)
              
              if (res.data.items.red_money == 0) {
                that.closeLayer()
              } else {
                that.setData({
                  redmoney: res.data.items.red_money
                })
              }
            }
          })
        }
  },
  resizeData:function(data){
    var that = this;
    var sysObj = {}
    
    sysObj = app.globalData.systemInfo
    //app.globalData.allInfo = Object.assign(app.globalData.userInfo, app.globalData.systemInfo)// 整合数据 这里的userInfo 是之前的默认数据
    app.globalData.userInfo = data // 重置数据,以便其他接口使用
    app.globalData.systemInfo = sysObj// 重置本机数据
    app.globalData.allInfo.uid = app.globalData.userInfo.uid
    // 发送 res.code 到后台换取 openId, sessionKey, unionId
  }
})

